import {onBeforeUnmount, ref} from 'vue'

export function useMove() {
    const left = ref('')
    const top = ref('')
    const width = ref('')
    const height = ref('')
    let x, y;

    function getParent(el, cls) {
        if(el.classList.contains(cls)) return el;
        return getParent(el.parentNode, cls)
    }
    function mousedown(e) {
        x = e.clientX
        y = e.clientY
        if(e.target.classList.contains('c-webrtc-chat-menu')) {
            const el = getParent(e.target, 'c-webrtc-content')
            if(el.classList.contains('maximize')) return;
            const rect = el.getBoundingClientRect()
            left.value = rect.left
            top.value = rect.top
            width.value = rect.width
            height.value = rect.height
            document.addEventListener('mousemove', mousemove)
            document.addEventListener('mouseup', mouseup)
        }
    }

    function mousemove(e) {
        let dx = e.clientX - x, dy = e.clientY - y
        left.value += dx
        top.value += dy
        x = e.clientX
        y = e.clientY
    }

    function mouseup() {
        document.removeEventListener('mousemove', mousemove)
        document.removeEventListener('mouseup', mouseup)
    }

    document.addEventListener('mousedown', mousedown)

    onBeforeUnmount(() => {
        document.removeEventListener('mousedown', mousedown)
    })
    return {
        left, top, width, height
    }
}